package com.my.socket.nio.v27;

import com.google.common.base.Throwables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;

/**
 * Created by Scarlett on 2018/8/20 0020.
 */
public class Server {
    private static final Logger LOGGER = LoggerFactory.getLogger(Server.class);

    private ServerSocketChannel serverSocketChannel;

    public Server(String hostname, int port) throws Exception {
        this.serverSocketChannel = ServerSocketChannel.open();
        this.serverSocketChannel.bind(new InetSocketAddress(hostname, port));
        this.serverSocketChannel.configureBlocking(false);
    }

    public void start() {
        for (int i = 0; i < 6; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Selector selector = Selector.open();
                        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

                        while (true) {
                            selector.select();

                            Set<SelectionKey> selectionKeys = selector.selectedKeys();
                            for (SelectionKey selectionKey : selectionKeys) {
                                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                                SocketChannel socketChannel = serverSocketChannel.accept();
                                if (socketChannel != null) {
                                    LOGGER.info("incoming socket: {}, selector: {}", socketChannel, selector);
                                }
                            }
                            selectionKeys.clear();
                        }
                    } catch (Exception e) {
                        LOGGER.error("exception caught, the error is {}", Throwables.getStackTraceAsString(e));
                    }
                }
            }).start();
        }
    }

    public static void main(String[] args) throws Exception {
        Server server = new Server("127.0.0.1", 9999);
        server.start();
    }
}
